package com.ktwlsoft.archivemanage.domain.business.businessService.study;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.study.StudySubjectRepositoryService;
import com.ktwlsoft.archivemanage.domain.dao.entity.Account;
import com.ktwlsoft.archivemanage.domain.dao.entity.study.StudySubject;
import com.ktwlsoft.archivemanage.domain.dao.entity.study.StudySubjectClass;
import com.ktwlsoft.archivemanage.domain.dao.repository.study.StudySubjectClassMapper;
import com.ktwlsoft.archivemanage.payload.exception.BusinessException;
import com.ktwlsoft.archivemanage.payload.study.subject.SaveSubjectClassRequest;
import com.ktwlsoft.archivemanage.payload.study.subject.SaveSubjectRequest;
import com.ktwlsoft.archivemanage.payload.study.subject.StudySubjectPayload;
import com.ktwlsoft.archivemanage.payload.study.subject.SubjectClassPayload;
import com.ktwlsoft.archivemanage.service.security.UserPrincipal;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class StudySubjectService {

    private final StudySubjectRepositoryService subjectRepositoryService;

    private final StudySubjectClassMapper subjectClassMapper;

    public StudySubjectService(StudySubjectRepositoryService subjectRepositoryService, StudySubjectClassMapper subjectClassMapper) {
        this.subjectRepositoryService = subjectRepositoryService;
        this.subjectClassMapper = subjectClassMapper;
    }

    @Transactional(rollbackFor = Exception.class)
    public SaveSubjectRequest save(SaveSubjectRequest request, String classType) {
        StudySubject studySubject;
        if ("ADD".equals(request.getPurpose())) {
            studySubject = new StudySubject(
                    request.getTitle(),
                    request.getTag(),
                    request.getMainImgUrl(),
                    classType,
                    request.getState());
            if("UP".equals(request.getState())){
                studySubject.setUp();
            }
            if (subjectRepositoryService.getStudySubjectMapper().insert(studySubject) <= 0) {
                throw new BusinessException("添加专题失败!");
            }
        } else if ("EDIT".equals(request.getPurpose())) {
            studySubject = subjectRepositoryService.getStudySubjectMapper().selectByPrimaryKey(request.getId());
            studySubject.update(request.getTitle(), request.getTag(), request.getMainImgUrl(), request.getState());
            subjectRepositoryService.getStudySubjectMapper().updateByPrimaryKey(studySubject);
        } else {
            throw new BusinessException("未找到合理的purpose");
        }
        for (SaveSubjectClassRequest r : request.getClasses()) {
            StudySubjectClass subjectClass;
            if ("ADD".equals(r.getPurpose())) {
                subjectClass = new StudySubjectClass(studySubject.getId(), r.getClassId(), r.getSort());
                if (subjectClassMapper.insert(subjectClass) <= 0) {
                    throw new BusinessException("建立专题与课程关系失败!");
                }
            }else if ("EDIT".equals(r.getPurpose())) {
                if(r.getSubjectId() == null) {
                    throw new BusinessException("subjectId不能为空!");
                }
                subjectClass = subjectClassMapper.selectByClassIdAndSubjectId(r.getClassId(), r.getSubjectId());
                subjectClass.setSort(r.getSort());
                subjectClassMapper.updateByPrimaryKey(subjectClass);
            }
            else if ("DELETE".equals(r.getPurpose())) {
                subjectClassMapper.deleteBySubjectIdAnClassId(r.getSubjectId(), r.getClassId());
            } else {
                throw new BusinessException("未找到合理的purpose");
            }
        }
        request.setId(studySubject.getId());
        return request;
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        int deleteResult = subjectRepositoryService.getStudySubjectMapper().deleteByPrimaryKey(id);
        subjectClassMapper.deleteBySubjectId(id);
        if (deleteResult <= 0) {
            throw new BusinessException("删除失败, 请检查id是否正确!");
        }
    }

    public PageInfo<StudySubjectPayload> getList(Integer pn, Integer pageSize, String keywords, String classType, String order) {
        PageHelper.startPage(pn, pageSize);
        return new PageInfo<>(subjectRepositoryService.getList(keywords, classType, order));
    }

    public int updown(Long id, String state) {
        Account user = UserPrincipal.getCurrentUser();
        return subjectRepositoryService.getStudySubjectMapper().changeState(id, state, user.getId(), user.getRealName());
    }

    @Transactional(rollbackFor = Exception.class)
    public StudySubjectPayload getById(Long id) {
        StudySubject subject = subjectRepositoryService.getStudySubjectMapper().selectByPrimaryKey(id);
        StudySubjectPayload subjectPayload = new StudySubjectPayload(
                subject.getId(),
                subject.getTitle(),
                subject.getTag(),
                0,
                subject.getState(),
                subject.getPublisherName(),
                subject.getPublishAt(),
                subject.getMainImgUrl()
        );
        // get subject class
        List<SubjectClassPayload> classPayloads = subjectRepositoryService.getStudySubjectMapper().selectClasses(id);
        subjectPayload.setClasses(classPayloads);
        return subjectPayload;
    }
}
